package com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark

import android.app.Activity
import android.content.Intent
import android.os.Handler
import android.text.Html
import android.text.TextPaint
import android.view.View
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.google.gson.Gson
import com.lancoo.cpbase.authentication.utils.AndroidBug5497Workaround
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkDialog.RemindDialog
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkDialog.ShowDialogTools
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.LancooMethod
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseActivity
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseFragmentPagerAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.bindLifeCycle
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.EvalBody
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.QuesMarkDeatil
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.QuesMarkInfor
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.Type
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.viewModel.EvalViewModel
import com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.aibkMarkJdt.MarkFragmentJdt
import com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.aibkMarkZht.MarkFragmentZht
import com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.aibkMarkZw.MarkFragmentZw
import com.lancoo.znbkxx.teacher.utils.DensityUtils
import kotlinx.android.synthetic.main.aibk_activity_ques_mark.*
import kotlinx.android.synthetic.main.aibk_activity_single_ques_evaluation.BtnBack
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.io.Serializable

class AibkQuesMarkActivity : KBaseActivity(), View.OnClickListener {

    private var setId = ""
    private var stuId = ""
    private var paperId = ""
    private var paperName = ""
    private var isOneOnOne = false
    private val ANSWERSHEET_CODE = 101
    private var indexA: Int = 0
    private var indexB: Int = 0
    private var indexC: Int = 0
    private var quesScoreInfor = ""
    private var typeListPosition = 0
    private var vpQuesPosition = 0
    private val mViewModel: EvalViewModel by viewModel()
    private var fragmentList: MutableList<Fragment>? = ArrayList()
    val evalBody = EvalBody()
    var isChange = false //判读是否已经有评阅
    var mTypeList: MutableList<Type>? = null
    private lateinit var remindDialog: RemindDialog

    companion object {
        fun launch(activity: Activity, setId: String, stuId: String, paperId: String, paperName: String, isOneOnOne: Boolean) {
            val intent = Intent(activity, AibkQuesMarkActivity::class.java)
            intent.putExtra("StuID", stuId)
            intent.putExtra("PaperID", paperId)
            intent.putExtra("PaperName", paperName)
            intent.putExtra("IsOneOnOne", isOneOnOne)
            intent.putExtra("setId", setId)
            activity.startActivity(intent)
        }
    }


    override fun setLayout(): Int {
        return R.layout.aibk_activity_ques_mark
    }

    override fun initView() {
        AndroidBug5497Workaround.assistActivity(this)
        BtnBack.setOnClickListener(this)
        BtnSave.setOnClickListener(this)
        TvQuesInfor.visibility = View.INVISIBLE
        TvQuesInfor.setOnClickListener(this)
        BtnAnswerSheet.setOnClickListener(this)
        remindDialog = RemindDialog(this, this, R.style.AppTheme_CommonDialog)
    }

    override fun initData() {
        setId = intent.getStringExtra("setId")
        stuId = intent.getStringExtra("StuID")
        paperName = intent.getStringExtra("PaperName")
        paperId = intent.getStringExtra("PaperID")
        isOneOnOne = intent.getBooleanExtra("IsOneOnOne", false)
        TvQuesName.setText(paperName)
        if (isOneOnOne) {
            mViewModel.getPaperForEval_1v1(stuId, paperId)
                    .doOnSubscribe {
                    }.bindLifeCycle(this)
                    .subscribe({
                        if (it.code == 1) {
                            mTypeList = it.data.TypeList
                            showQuesMarkView(it.data)
                        } else {
                            MyToast.showToast(it.message)
                            Handler().postDelayed({
                                finish()
                            }, 1000)
                        }
                    }, {
                        MyToast.showToast(it.message)
                        Handler().postDelayed({
                            finish()
                        }, 1000)
                    })
        } else {
            mViewModel.getPaperForEval(paperId, setId)
                    .doOnSubscribe {
                    }.bindLifeCycle(this)
                    .subscribe({
                        if (it.code == 1) {
                            mTypeList = it.data.TypeList
                            showQuesMarkView(it.data)
                        } else {
                            MyToast.showToast(it.message)
                            Handler().postDelayed({
                                finish()
                            }, 1000)
                        }
                    }, {
                        MyToast.showToast(it.message)
                        Handler().postDelayed({
                            finish()
                        }, 1000)
                    })
        }
    }


    private fun showQuesMarkView(quesMarkInfor: QuesMarkInfor) {
        LlToolsView.visibility = View.VISIBLE
        TvQuesName.text = "试卷评阅"
        TvQuesInfor.visibility = View.VISIBLE
        //加载试题,显示试卷作答情况
        fragmentList?.clear()
        val typeListSize = quesMarkInfor.TypeList.size
        for (i in 0 until typeListSize) {
            val typeNo = quesMarkInfor.TypeList[i].TypeNo
            val quesListSize = quesMarkInfor.TypeList[i].QuesList.size
            for (j in 0 until quesListSize) {
                val quesId = quesMarkInfor.TypeList[i].QuesList[j].QuesID
                val startIndex = quesMarkInfor.TypeList[i].QuesList[j].SortIndexList[0].SortIndex.split("-")[0]
                if (typeNo == "k") {
                    val mFragment = MarkFragmentZht(i, j, this, quesId, startIndex).apply { }
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                } else if (typeNo == "f" || typeNo == "H") {
                    val mFragment = MarkFragmentZw(i, j, this, quesId, startIndex)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                } else if (typeNo == "Q" || typeNo == "b" || typeNo == "d"
                        || typeNo == "X" || typeNo == "g" || typeNo == "V"
                        || typeNo == "G" || typeNo == "N" || typeNo == "S"
                        || typeNo == "U") {//Q:阅读填空,X:阅读简答,G:听力简答,
                    val mFragment = MarkFragmentJdt(i, j, this, quesId, startIndex)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                }
            }
        }
        val mAdapter = KBaseFragmentPagerAdapter(supportFragmentManager, fragmentList as ArrayList<Fragment>)
        VpQuesMark.adapter = mAdapter
        VpQuesMark.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                vpQuesPosition = position
                showQuesTitleInfor(quesMarkInfor)
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })

        showQuesTitleInfor(quesMarkInfor)
    }

    private fun showQuesTitleInfor(quesMarkInfor: QuesMarkInfor) {
        typeListPosition = MarkInforIndexHelp.QuesPosition_return_TypeListPosition(quesMarkInfor, vpQuesPosition)

        val typeIndex = quesMarkInfor.TypeList[typeListPosition].TypeIndex
        val strTypeIndex = LancooMethod.numberToChinese(typeIndex)
        var genreName = quesMarkInfor.TypeList[typeListPosition].GenreName
        val typeName = quesMarkInfor.TypeList[typeListPosition].TypeName
        if (genreName.isEmpty()) {
            genreName = typeName
        }
        /******************************************************************************************/
        var totalChildQuesSize = 0
        var totalChildQuesScore = 0.0
        val quesListSize = quesMarkInfor.TypeList[typeListPosition].QuesList.size
        for (i in 0 until quesListSize) {
            val sortIndexListSize = quesMarkInfor.TypeList[typeListPosition].QuesList[i].SortIndexList.size
            totalChildQuesSize += sortIndexListSize

            for (j in 0 until sortIndexListSize) {
                val score = quesMarkInfor.TypeList[typeListPosition].QuesList[i].SortIndexList[j].Score
                totalChildQuesScore += score
            }
        }

        var isAverage = true
        val averageScore = LancooMethod.getCorrectRateInt(totalChildQuesScore, totalChildQuesSize)
        outLoop@ for (i in 0 until quesListSize) {
            val sortIndexListSize = quesMarkInfor.TypeList[typeListPosition].QuesList[i].SortIndexList.size
            for (j in 0 until sortIndexListSize) {
                val score = quesMarkInfor.TypeList[typeListPosition].QuesList[i].SortIndexList[j].Score
                if (score != averageScore) {
                    isAverage = false
                    break@outLoop
                }
            }
        }

        if (isAverage) {
            TvQuesInfor.text = Html.fromHtml(resources.getString(R.string.aibk_practice_ques_infor_short,
                    strTypeIndex, genreName, quesListSize, totalChildQuesSize, averageScore.toString()))
        } else {
            var childScoreAll = ""
            val quesListSize = quesMarkInfor.TypeList[typeListPosition].QuesList.size
            for (x in 0 until quesListSize) {
                val sortIndexListSize = quesMarkInfor.TypeList[typeListPosition].QuesList[x].SortIndexList.size
                for (y in 0 until sortIndexListSize) {
                    val sortIndex = quesMarkInfor.TypeList[typeListPosition].QuesList[x].SortIndexList[y].SortIndex
                    val score = quesMarkInfor.TypeList[typeListPosition].QuesList[x].SortIndexList[y].Score
                    val childScore = resources.getString(R.string.aibk_single_ques_infor, sortIndex, score.toString())
                    if (childScoreAll.isEmpty()) {
                        childScoreAll = childScore
                    } else {
                        childScoreAll = "$childScoreAll,$childScore"
                    }
                }

                TvQuesInfor.text = Html.fromHtml(resources.getString(R.string.aibk_practice_ques_infor_long,
                        strTypeIndex, genreName, quesListSize, totalChildQuesSize, childScoreAll))
            }
        }
        /******************************************************************************************/
    }

    /*
    * 获取单个题目的试题详情
    * */
    fun getSingQuesMarkDetail(quesId: String, startIndex: String) {
        if (isOneOnOne) {
            mViewModel.getQuesForEval_1v1(stuId, paperId, quesId, startIndex)
                    .doOnSubscribe {
                    }.bindLifeCycle(this)
                    .subscribe({
                        if (it.code == 1) {
                            detailListener!!.getQuesDetailSuccess(it.data)
                        } else {
                            MyToast.showToast(it.message)
                            Handler().postDelayed({
                                finish()
                            }, 500)
                        }
                    }, {
                        MyToast.showToast(it.message)
                        Handler().postDelayed({
                            finish()
                        }, 500)
                    })
        } else {
            mViewModel.getQuesForEval(setId, paperId, quesId, startIndex)
                    .doOnSubscribe {
                    }.bindLifeCycle(this)
                    .subscribe({
                        if (it.code == 1) {
                            detailListener!!.getQuesDetailSuccess(it.data)
                        } else {
                            MyToast.showToast(it.message)
                            Handler().postDelayed({
                                finish()
                            }, 500)
                        }
                    }, {
                        MyToast.showToast(it.message)
                        Handler().postDelayed({
                            finish()
                        }, 500)
                    })
        }
    }

    interface OnDetailListener {
        fun getQuesDetailSuccess(quesMarkDeatil: QuesMarkDeatil)
        fun getQuesDetailFaile()
    }

    private var detailListener: OnDetailListener? = null

    fun setDetailListener(onDetailListener: OnDetailListener?) {
        this.detailListener = onDetailListener
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.BtnBack -> {
                if (isChange) {
                    remindDialog.setOnClickListener(object : RemindDialog.OnClickListener {
                        override fun onConfirm() {
                            savePaperEval(true)
                        }

                        override fun onCancel() {
                            finish()
                        }
                    }).show()
                } else {
                    finish()
                }
            }
            R.id.BtnSave -> {
                if (isChange) {
                    savePaperEval(false)
                } else {
                    MyToast.showToast("暂未评阅，无需保存")
                }
            }
            R.id.TvQuesInfor -> {
                quesScoreInfor = TvQuesInfor.text.toString()
                val mTextPaint: TextPaint = TvQuesInfor.paint
                mTextPaint.textSize = TvQuesInfor.textSize
                val mTextViewWidth = mTextPaint.measureText(quesScoreInfor).toInt()
                val mTvQuesInforWidth = TvQuesInfor.width - DensityUtils.dp2px(this, 20f)
                if (mTextViewWidth > mTvQuesInforWidth) { //超出一行
                    ShowDialogTools.showQuesScoreInofrDialog(this, quesScoreInfor)
                }
            }
            R.id.BtnAnswerSheet -> {
                val intent = Intent(this, AnswerSheetActivity::class.java).apply {
                    putExtra("TypeList", mTypeList as Serializable)
                }
                startActivityForResult(intent, ANSWERSHEET_CODE)
            }
        }
    }

    private fun savePaperEval(ifFinish: Boolean) {
        mViewModel.savePaperEval(getEvalData())
                .doOnSubscribe {
                }.bindLifeCycle(this)
                .subscribe({
                    if (it.code == 1) {
                        MyToast.showToast("保存成功")
                        if (ifFinish) {
                            finish()
                        }
                    } else {
                        MyToast.showToast(it.message)
                    }
                }, {
                    MyToast.showToast(it.message)
                })
    }

    private fun getEvalData(): RequestBody {
        evalBody.SetID = setId
        evalBody.paperID = paperId
        evalBody.globalGrade = Ext.GLOBAL_GRADE
        val evalGson = Gson()
        return RequestBody.create("application/json; charset=utf-8".toMediaTypeOrNull(), evalGson.toJson(evalBody))
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 101) {//从语法专项选择页面返回到组卷主页面时，刷新界面中语法专项选中状态
            if (data != null) {
                indexA = data.getIntExtra("indexA", 0)
                indexB = data.getIntExtra("indexB", 0)
                indexC = data.getIntExtra("indexC", 0)
                jumpItem()
            }
        }
    }

    private fun jumpItem() {
        val typeListSize = mTypeList!!.size
        var index = 0
        for (i in 0 until typeListSize) {
            val quesListSize = mTypeList!![i].QuesList.size
            for (j in 0 until quesListSize) {
                if (i == indexA && indexB == j) {
                    VpQuesMark.setCurrentItem(index, true)
                    if (mTypeList!![indexA].TypeNo == "k") {
                        (fragmentList!![index] as MarkFragmentZht).scrollToPosition(indexC)
                    } else if (mTypeList!![indexA].TypeNo == "f" || mTypeList!![indexA].TypeNo == "H") {
                        (fragmentList!![index] as MarkFragmentZw).scrollToPosition(indexC)
                    } else if (mTypeList!![indexA].TypeNo == "Q" || mTypeList!![indexA].TypeNo == "b" || mTypeList!![indexA].TypeNo == "d"
                            || mTypeList!![indexA].TypeNo == "X" || mTypeList!![indexA].TypeNo == "g" || mTypeList!![indexA].TypeNo == "V"
                            || mTypeList!![indexA].TypeNo == "G" || mTypeList!![indexA].TypeNo == "N" || mTypeList!![indexA].TypeNo == "S"
                            || mTypeList!![indexA].TypeNo == "U") {//Q:阅读填空,X:阅读简答,G:听力简答,
                        (fragmentList!![index] as MarkFragmentJdt).scrollToPosition(indexC)
                    }
                    return
                }
                index++
            }
        }
    }

    override fun onBackPressed() {
        if (isChange) {
            remindDialog.setOnClickListener(object : RemindDialog.OnClickListener {
                override fun onConfirm() {
                    savePaperEval(true)
                }

                override fun onCancel() {
                    finish()
                }
            }).show()
        } else {
            finish()
        }
    }

}